package com.itheima.reggin.controller;

import com.itheima.reggin.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 图片的上传下载
 */
@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {

    @Value("${reggin.path}")
    private String basePath;


    /**
     * 文件上传的方法
     * @param file   这个参数的名字不能改变
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        //file  是一个临时文件    本次请求完成之后  需要转存到指定的路径，否则就会删除
        //原始文件名字
        String originalFileName = file.getOriginalFilename();//如果文件名字重复就会覆盖
        //获取文件类型后缀
        String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));

        //使用uuid生成文件名字
        String fileName = UUID.randomUUID().toString() + suffix;

        File dir = new File(basePath);
        if (!dir.exists()) {
            //创建
            dir.mkdirs();
        }
        System.out.println(basePath + fileName);
        file.transferTo(new File(basePath + fileName));
        return R.success(fileName);

    }


    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            //输入刘  读取文件的内容
            FileInputStream fileInputStream = new FileInputStream(basePath + name);

            //输出刘
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");
            int len;
            byte[] bytes = new byte[1024];

            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
            fileInputStream.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
